#ifndef HEADERS_H_INCLUDED
#define HEADERS_H_INCLUDED

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <curl/curl.h>
#include <curl/easy.h>

#define MAXBUFSIZE 1024
#define RIO_BUFSIZE 8192

#define oops(s) {  perror(s); exit(1); }

typedef struct
{
    int rio_fd;                /* descriptor for this internal buf */
    int rio_cnt;               /* unread bytes in internal buf */
    char *rio_bufptr;          /* next unread byte in internal buf */
    char rio_buf[RIO_BUFSIZE]; /* internal buffer */
} rio_t;


typedef struct
{
    char *memory;
    size_t size;
} MemoryStruct;

typedef struct
{
    FILE *stream;
    size_t size;
} FileStruct;


typedef struct curl_slist * HttpHeader;

typedef struct CURL * Handle;

void CURLoops(CURLcode code  , const char * str)
{
    if (code != CURLE_OK)
    {
        fprintf(stderr, "set %s failed : %s \n",  str , curl_easy_strerror(code));
        exit(1);
    }
}

static size_t
writeFileCallback(void *ptr, size_t size, size_t nmemb, void *stream)
{
    FileStruct * file = (FileStruct *)stream;
    size_t written = fwrite(ptr, size, nmemb, file->stream);
    file->size = size * nmemb;
    return written;
}

static size_t
WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    size_t realsize = size * nmemb;
    MemoryStruct *mem = (MemoryStruct *)userp;

    mem->memory = realloc(mem->memory, mem->size + realsize + 1);
    if(mem->memory == NULL)
    {
        /* out of memory! */
        printf("not enough memory (realloc returned NULL)\n");
        return 0;
    }

    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;
}

#endif // HEADERS_H_INCLUDED
